<template>
  <div class="OrderCreate">
    <van-nav-bar title="填写订单" left-arrow @click-left="onClickLeft" />
   <template v-if="showAddress">
      <van-cell-group>
      <van-cell :title="finalAddress" @click="onEdit" />
      <van-cell
        :title="currentContact.addressDetail"
        @click="onEdit"
        is-link
        :label="finalContact"
      />
    </van-cell-group>
   </template>
    <template v-else>
       <van-cell title="请先选择收货地址" @click="onEdit" />
    </template>
    <div class="CartList">
      <template v-for="(item, index) in cartList">
        <van-card
          class="CartList-item"
          :key="index"
          :num="item.number"
          :price="(item.price * item.number).toFixed(2)"
          :title="item.goodsName"
          :thumb="item.picUrl"
        />
      </template>
    </div>

    <van-cell-group>
      <van-cell title="商品金额" :value="'￥' + totalPrice.toFixed(2)" />
      <van-cell title="发票" value="个人" is-link />
    </van-cell-group>

    <van-submit-bar
      :price="totalPrice * 100"
      button-text="提交订单"
      @submit="onSubmit"
    />
  </div>
</template>

<script>
import {
  NavBar,
  ContactCard,
  Card,
  Cell,
  CellGroup,
  SubmitBar,
  Toast,
} from "vant";
import {
  getShoppingCart,
  getAddress,
  getAddressDetail,
  orderSubmit,
  getGoodsDetail
} from "@/network/index.js";
export default {
  name: "OrderCreate",
  data() {
    return {
      currentContact: {},
      cartList: [],
    };
  },
  computed: {
    showAddress() { //是否有地址信息
    return JSON.stringify(this.currentContact) === '{}' ? false : true
    },
    finalContact() {
      //组合联系人名字和号码
      return this.currentContact.name + " " + this.currentContact.tel;
    },
    totalPrice() {
      //计算总价
      let total = 0;
      for (let i of this.cartList) {
        total += i.price * i.number;
      }
      return total;
    },
    finalAddress() {
      //组合详细收货地址
      return (
        this.currentContact.province +
        this.currentContact.city +
        this.currentContact.county
      );
    },
  },
  components: {
    [NavBar.name]: NavBar,
    [ContactCard.name]: ContactCard,
    [Card.name]: Card,
    [Cell.name]: Cell,
    [CellGroup.name]: CellGroup,
    [SubmitBar.name]: SubmitBar,
    [Toast.name]: Toast,
  },
  methods: {
    onClickLeft() {
      this.$router.back();
    },
    onEdit() {
      // 跳转至地址选择页面
      this.$router.push({ name: "Contact" });
    },
    //提交订单
    async onSubmit() {
      const arr = [];
      for (let i of this.cartList) {
        Array.prototype.push.call(arr, i.id);
      }
    if(this.$route.query.cartId) {
      const info = {
        cartId: this.$route.query.cartId,
        addressId: this.currentContact.id,
      };
      const { data } = await orderSubmit(info);
      if (data.errno === 0) {
       Toast.success('订单提交成功');
       this.$router.push({name: 'OrderList'})
      }
    }else {
        const info = {
        cartId: arr,
        addressId: this.currentContact.id,
      };
      const { data } = await orderSubmit(info);
      if (data.errno === 0) {
       Toast.success('订单提交成功');
       this.$router.back()
      }
    }
    },
    async acquireAddress() {
      //获取地址信息
      if (!this.$store.state.AddressId) {
        //如果vuex中没有有地址id就直接请求
        const {
          data: { data },
        } = await getAddress();
        for (let i of data.list) {
          //把默认地址拿出来
          if (i.isDefault) {
            this.currentContact = i;
          }
        }
      } else {
        // 根据地址id来拿地址详情
        const info = {
          id: this.$store.state.AddressId,
        };
        const {
          data: { data },
        } = await getAddressDetail(info);
        data.address = data.province + data.city + data.county;
        this.currentContact = data;
        this.$store.commit("setAddressId", 0); //初始化vuex地址id
      }
    },
    async getCartInfo() {
      //获取购物车数据
      const {
        data: { data },
      } = await getShoppingCart();
        for(let i of data.cartList) { //遍历请求下来的购物车数组
          if(i.checked) { //如果购物车数组里面有已经选中的
            this.cartList.push(i) //把选中的购物车项放进当前页面的购物车数组进行渲染
          }
        }
      
    },
  },
  async created() {
    const address = this.$store.state.address //获取vuex中的地址信息
    if(address) {  //如果存在
      this.currentContact = address //直接保存进当前地址进行渲染
    }else { //如果不存在就请求获取
       this.acquireAddress(); //获取地址信息
    }
    const {data:{data}} = await getGoodsDetail({id:this.$store.state.atOnceId})
    const number = this.$route.query.number //路由获取数量
    if(this.$store.state.atOnceId) { //如果获取到了信息说明是从立即购买页面跳转过来的
      data.info.number = number  //设置数量
      data.info.name = data.info.goodsName //设置商品名称
      data.info.price = data.info.retailPrice //设置商品价格
      this.cartList.push(data.info) //推进购物车商品数组里面进行渲染
    }else { //没有信息说明是从购物车界面跳转过来的即必须获取购物车数据
      this.getCartInfo(); //获取购物车信息
    }
  },
  mounted() {
  },
};
</script>

<style lang="less" scoped>
.OrderCreate {
  background: rgb(233, 232, 232);
}
.CartList {
  margin-top: 10px;
  .CartList-item {
    width: 95%;
    border-radius: 15px;
    margin: 10px auto;
  }
}
</style>

